package com.hellobike.haxing.modules.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.product.entity.SkuStock;
import com.hellobike.haxing.modules.product.mapper.SkuStockMapper;
import com.hellobike.haxing.modules.product.service.ISkuStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @Description: 销售库存
 * @Author: haxing-boot
 * @Date:   2020-02-10
 * @Version: V1.0
 */
@Service
public class SkuStockServiceImpl extends ServiceImpl<SkuStockMapper, SkuStock> implements ISkuStockService {

    @Autowired
    private SkuStockMapper skuStockMapper;

    @Override
    public Result changeCitySkuStock(Long cityId, Long skuId, Integer changeNum) {
        if (changeNum == 0) {
            return Result.ok();
        }
        QueryWrapper<SkuStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SkuStock::getCityId, cityId).eq(SkuStock::getSkuId, skuId);
        SkuStock skuStock = skuStockMapper.selectOne(queryWrapper);
        if (skuStock != null) {
            int flag = skuStockMapper.changeSkuStock(skuId, cityId, changeNum);
            if (flag == 0) {
                return Result.error("库存不足");
            }
        } else {
            if (changeNum < 0) {
                return Result.error("库存不足");
            } else {
                SkuStock newSkuStock = new SkuStock();
                newSkuStock.setSkuId(skuId);
                newSkuStock.setCityId(cityId);
                newSkuStock.setStock(changeNum);
                skuStockMapper.insert(newSkuStock);
            }
        }
        return Result.ok();
    }

}
